package com.chenggong.demo.permission

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.chenggong.demo.R
import com.fengsu.baselib.permission.AuthorityEntity
import java.util.*


object PermissionUtils {
    private const val REQUEST_CODE = 123
    private var isOpenPermission = false

    /**
     * 判断选权限
     *
     * @param activity    Activity
     * @param permissions 多个权限
     * @return
     */
    @JvmStatic
    fun checkPermission(context: Context?, permissions: Array<String>): Boolean {
        val permissionsList: MutableList<String> = ArrayList()
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(
                            context!!,
                            permission
                    ) != PackageManager.PERMISSION_GRANTED
            ) {
                permissionsList.add(permission)
            }
        }
        return permissionsList.isEmpty()
    }

    /**
     * 判断单个权限
     *
     * @param activity    Activity
     * @param permissions 多个权限
     * @return
     */
    fun checkSinglePermission(context: Context?, permission: String): Boolean {
        return ContextCompat.checkSelfPermission(
                context!!,
                permission
        ) == PackageManager.PERMISSION_GRANTED
    }

    /**
     * 申请权限
     *
     * @param activity    Activity
     * @param permissions 多个权限
     */
    @JvmStatic
    fun getPermission(activity: Activity?, permissions: Array<String>) {
        val permissionsList: MutableList<String> = ArrayList()
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(
                            activity!!,
                            permission
                    ) != PackageManager.PERMISSION_GRANTED
            ) {
                permissionsList.add(permission)
            }
        }
        if (permissionsList.isEmpty()) {
            permissionObserverMap[activity.toString()]?.authorizationSuccess()
        } else {
            if (!isOpenPermission) {
                ActivityCompat.requestPermissions(
                        activity!!,
                        permissionsList.toTypedArray(),
                        REQUEST_CODE
                )
            } else {
                permissionObserverMap[activity.toString()]?.authorizationFailure()
            }
        }
    }

    /**
     * 此方法必须再Activity中onRequestPermissionsResult调用
     * @param activity Activity
     * @param requestCode 返回值
     * @param permissions 返回权限集合
     * @param grantResults 是否授权集合
     */
    fun onRequestPermissionsResult(
            activity: Activity,
            requestCode: Int,
            permissions: Array<out String>,
            grantResults: IntArray
    ) {
        val permissionMap: MutableMap<String, String> = HashMap()
        val firstPermissionMap: MutableMap<String, Int> = HashMap()
        if (requestCode == REQUEST_CODE) {
            for (i in grantResults.indices) {
                firstPermissionMap[permissions[i]] = grantResults[i]
                //判断是否成功
                if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                    //判断是否有禁止选项
                    if (!ActivityCompat.shouldShowRequestPermissionRationale(
                                    activity,
                                    permissions[i]
                            )
                    ) {
                        permissionMap[permissions[i]] = "forbid"
                    } else {
                        permissionMap[permissions[i]] = "allow"
                    }
                }
            }
        }
        if (permissionMap.isEmpty()) {
            permissionObserverMap[activity.toString()]?.authorizationSuccess()
            isOpenPermission = false
        } else {
            if (permissionMap.containsValue("forbid")) {
                val sharedPreferences =
                        activity.getSharedPreferences("kotlin_pdf_changer", Context.MODE_PRIVATE)
                if (!sharedPreferences.getBoolean("first_permission_auth", true)) {
                    val packageURI = Uri.parse("package:" + activity.packageName)
                    val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI)
                    activity.startActivity(intent)
                } else {
                    val edit = sharedPreferences.edit().putBoolean("first_permission_auth", false)
                    edit.apply()
                }
                if (activity.localClassName == "ui.ToolsDispenseActivity") {
                    activity.finish()
                }
//                showPermissionDialog(activity)

            } else {
                Toast.makeText(
                        activity,
                        activity.getString(R.string.please_permission),
                        Toast.LENGTH_LONG
                ).show()
                permissionObserverMap[activity.toString()]?.authorizationFailure()
                isOpenPermission = false
            }
        }
        permissionObserverMap[activity.toString()]?.firstAuthorization(firstPermissionMap)

    }


    private val permissionObserverMap = HashMap<String, PermissionObserver>()
    fun setOnPermissionsListener(
            activity: Activity,
            permissionObserver: PermissionObserver
    ): PermissionUtils {
        permissionObserverMap[activity.toString()] = permissionObserver
        return this
    }

    fun setOnPermissionsListener(
            activity: Activity, authorizationSuccess: (() -> Unit)? = null,
            authorizationFailure: (() -> Unit)? = null,
            firstAuthorization: ((map: Map<String, Int>) -> Unit)? = null
    ): PermissionUtils {
        val permissionObserver = object : PermissionObserver {
            override fun authorizationSuccess() {
                authorizationSuccess?.invoke()
            }

            override fun authorizationFailure() {
                authorizationFailure?.invoke()
            }

            override fun firstAuthorization(map: Map<String, Int>) {
                firstAuthorization?.invoke(map)
            }
        }
        setOnPermissionsListener(activity, permissionObserver)
        return this
    }

    /**
     * 相册检查权限并处理
     */
    fun checkSinglePermission(
        activity: Activity,
        permission: AuthorityEntity.AuthorityName,
        toDetail: () -> Unit,
        showAuthDialog: () -> Unit
    ) {
        if (!checkPermission(
                        activity,
                        getRequestPermissionList(permission)
                )
        ) {
            showAuthDialog.invoke()
        } else {
            toDetail.invoke()
        }
    }


    /**
     * 授权操作
     */
    fun authPermissions(activity: Activity, permission: AuthorityEntity.AuthorityName, toDetail: () -> Unit) {
        setOnPermissionsListener(
                activity,
                authorizationSuccess = {
                    toDetail.invoke()
                }).getPermission(
                activity,
                getRequestPermissionList(permission))
    }

    private fun getRequestPermissionList(permission: AuthorityEntity.AuthorityName): Array<String> {
        return when (permission) {
            AuthorityEntity.AuthorityName.EXTERNAL_STORAGE -> {
                arrayOf(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                )
            }
            AuthorityEntity.AuthorityName.CAMERA -> {
                arrayOf(
                        Manifest.permission.CAMERA
                )
            }
        }
    }
}